package com.zy.ems.common.util;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MD5工具类。
 * 
 * @author Luffy
 *
 */
public class Md5Util {

    private final static Logger logger = LoggerFactory.getLogger(Md5Util.class);

    private final static int PASSWORD_SALT_LENGTH = 6;

    private final static String SALT_SEED = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**
     * Calculates the MD5 digest and returns the value as a 32 character hex
     * string.
     * 
     * @param data
     * @return
     */
    public static String getMd5Hex(String data) {
        return DigestUtils.md5Hex(StringUtils.defaultString(data));
    }

    /**
     * 按规则生成密码的MD5码。
     * 
     * @param password
     * @param salt
     * @return
     */
    public static String getPasswordMd5(String password, String salt) {
        String pwd = StringUtils.defaultString(password);
        String slt = StringUtils.defaultString(salt);
        // MD5(原始密码的MD5 + salt)
        return DigestUtils.md5Hex(DigestUtils.md5Hex(pwd).concat(slt));
    }

    // 手机号码验证
    public static boolean isMobileNumber(String mobiles) {
        // Pattern p =
        // Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Pattern p = Pattern.compile(
                "^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 获取加密
     * 
     * @param length
     * @return
     */
    public static String getPasswordSalt() {
        String result = "";

        try {
            result = RandomStringUtils.random(PASSWORD_SALT_LENGTH, SALT_SEED);

            return result;
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);

            Random random = new Random();
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < PASSWORD_SALT_LENGTH; i++) {
                int number = random.nextInt(62);
                sb.append(SALT_SEED.charAt(number));
            }

            result = sb.toString();
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(getPasswordSalt());
    }
}
